namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Globalization;
    using System.Web.Mvc;
    using System.Web.Routing;
    using SimpleWebServices.Data;
    using SimpleWebServices.Globalization;
    using SimpleWebServices.Web;
    using SimpleWebServices.Web.Routing;

    public abstract class TenantController<T> : TenantController, IControlResource<T>
        where T : IResource
    {
        public virtual IConvertUri Converter
        {
            get
            {
                return new ImplicitUriConverter<T>(this.GetType());
            }
        }

        public virtual void Register(RouteCollection routes)
        {
            if (null == routes)
            {
                throw new ArgumentNullException("routes");
            }

            routes.Add(new ResourceRoute<T>(this.GetType()));
        }

        public T Model(CultureInfo language)
        {
            language.SetCurrentCulture();

            T model = Record.Retrieve<T>(this.Converter.Urn);

            return model;
        }

        public ActionResult Redirect(T model)
        {
            ActionResult result = null;

            if (null != model)
            {
                IRedirect redirect = model as IRedirect;
                if (null != redirect)
                {
                    result = redirect.ToActionResult();
                }
            }

            return result;
        }

        [ContentNegotiation(".html", "*/*, text/*, text/html")]
        public virtual ActionResult HtmlRepresentation(CultureInfo language)
        {
            T model = this.Model(language);

            return this.Redirect(model) ?? HtmlView(language, model.ApplyDefaultValues<T>());
        }

        [ContentNegotiation(".xhtml", "application/xhtml+xml")]
        public virtual ActionResult XhtmlRepresentation(CultureInfo language)
        {
            T model = this.Model(language);

            return this.Redirect(model) ?? XhtmlView(language, model.ApplyDefaultValues<T>());
        }
    }
}